package top.haijunit.work.configurer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.haijunit.work.core.doamin.Result;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 统一返回结果包装类
 *
 * @author zhanghaijun
 * @since 2024-08-07
 */
@Slf4j
@ControllerAdvice(annotations = RestController.class)
public class GlobalRestResultWrapper implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = methodParameter.getMethod();
        if (Objects.isNull(method)) {
            return false;
        }
        Class<?> returnType = method.getReturnType();
        if (returnType == ModelAndView.class
            || returnType == Void.TYPE
            || returnType == String.class
            || returnType == Result.class
            || Result.class.isAssignableFrom(returnType)
            || returnType == ResponseEntity.class) {
            return false;
        }
        return !method.getDeclaringClass().getName().contains("springdoc");
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return Result.success(body);
    }
}
